package cn.com.hnisi.springldap;

import java.util.LinkedList;
import java.util.List;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;

import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;

/**
 * 
 * @author yanping
 * 
 */
public class PersonDaoLdapImpl {

	// private static final String SEARCH_FILTER = "(CN=D_002301)";

	private static final String SEARCH_FILTER = "(CN=191803)";

	private static final String FILTER_4_LIST = "o=sdga";

	private LdapTemplate ldapTemplate;

	public void setLdapTemplate(LdapTemplate ldapTemplate) {
		this.ldapTemplate = ldapTemplate;
	}

	@SuppressWarnings(value = "unchecked")
	public List<String> getAllPersonNames() {
		return ldapTemplate.search("", SEARCH_FILTER, new AttributesMapper() {
			public Object mapFromAttributes(Attributes attrs)
					throws NamingException {
				return attrs.get("cn").get();
			}
		});
	}

	/**
	 * 
	 */
	public void getAllPersonNames1() {
		List<String> list = ldapTemplate.list("o=sdga");
		List templist = new LinkedList();
		for (String e : list) {
			templist = ldapTemplate.search("", e, new AttributesMapper() {
				public Object mapFromAttributes(Attributes attrs)
						throws NamingException {
					return attrs.get("uid").get();
				}
			});
			for (Object o : templist) {
				System.out.println(o);
			}
		}
	}

	/**
	 * 
	 */
	public List<Person> getAllPersons() {
		List<String> list = ldapTemplate.list(FILTER_4_LIST);
		List<Object> temp = new LinkedList<Object>();
		List<Person> persons = new LinkedList<Person>();
		for (String e : list) {
			temp = ldapTemplate.search("", e, new PersonAttributeMapper());
			for (Object o : temp) {
				persons.add((Person) o);
			}
		}
		return persons;
	}

	public Person findPerson(String dn) {
		return (Person) ldapTemplate.lookup(dn, new PersonAttributeMapper());
	}

	private class PersonAttributeMapper implements AttributesMapper {
		@Override
		public Object mapFromAttributes(Attributes attrs)
				throws NamingException {
			Person person = new Person();
			if (attrs.get("uid") != null) {
				person.setUid((String) attrs.get("uid").get());
			}
			if (attrs.get("cn") != null) {
				person.setCn((String) attrs.get("cn").get());
			}
			if (attrs.get("sn") != null) {
				person.setSn((String) attrs.get("sn").get());
			}
			if (attrs.get("mail") != null) {
				person.setMail((String) attrs.get("mail").get());
			}
			if (attrs.get("maildomain") != null) {
				person.setMaildomain((String) attrs.get("maildomain").get());
			}
			return person;
		}
	}

}
